package com.canbot.u05.activity.shoppingGuide.merchandiseShoppingGuide;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.bean.Merchandise;
import com.canbot.u05.bean.sales.ChoosePicBean;
import com.canbot.u05.network.SalesApi;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 商品内容编辑界面
 */
public class EditMerchandiseActivity extends BaseActivityNoTitle implements View.OnClickListener {

        private final static String TAG = "EditMerchandiseActivity";

        private final static int RESULT_CODE_PIC = 104;

        private final static int RESULT_CODE_VOICE = 105;

        private TextView textView;

        private Button btnBack;

        private Button btnSure;

        private TextView tvPic, tvAudio;

        private Merchandise merchandise;

        private Dialog dialogLoading;

        private boolean isEdit;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_edit_merchandise);
                setViews();
                isEdit = getIntent().getBooleanExtra("isEdit", false);
                if (isEdit) {
                        //编辑
                        String js = getIntent().getStringExtra("data");
                        if (!TextUtils.isEmpty(js)) {
                                Logger.e(TAG, "接收数据=" + js);
                                merchandise = JSON.parseObject(js, Merchandise.class);
                                textView.setText(merchandise.getTitle());
                        }
                }
                else {
                        boolean isSuccess = MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.SHOPPING_GUIDE_DIR + "merchandise/spnrbj_spdg_u05_001.wav");
                        if (!isSuccess) {
                                ToastTools.newInstance(this).showText(getString(R.string.network_error));
                        }
                        //新增
                        String title = getIntent().getStringExtra("title");
                        if (!TextUtils.isEmpty(title)) {
                                Logger.e(TAG, "接收数据title=" + title);
                                textView.setText(title);
                                merchandise = new Merchandise();
                                String uuid = UUID.randomUUID().toString().replace("-", "");
                                merchandise.setId(uuid);
                                merchandise.setTitle(title);
                        }
                }
        }

        private void setViews() {
                textView = (TextView) findViewById(R.id.tv_title);
                btnBack = (Button) findViewById(R.id.btn_back);
                btnSure = (Button) findViewById(R.id.btn_complete);
                tvPic = (TextView) findViewById(R.id.tv_add_pic);
                tvAudio = (TextView) findViewById(R.id.tv_add_voice);

                btnBack.setOnClickListener(this);
                btnSure.setOnClickListener(this);
                tvAudio.setOnClickListener(this);
                tvPic.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
                switch (view.getId()) {
                        case R.id.btn_back:
                                //返回
                                finish();
                                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                                break;
                        case R.id.btn_complete:

                                if (TextUtils.isEmpty(merchandise.getPic())) {
                                        boolean isSuccess = MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.SHOPPING_GUIDE_DIR + "merchandise/wsptp_spdg_u05_001.wav");
//                                        if (!isSuccess) {
                                        ToastTools.newInstance(this).showText(getString(R.string.please_select_picture));
//                                        }
                                        return;
                                }
                                if (TextUtils.isEmpty(merchandise.getVoice())) {
                                        boolean isSuccess = MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.SHOPPING_GUIDE_DIR + "merchandise/wspyy_spdg_u05_001.wav");
//                                        if (!isSuccess) {
                                        ToastTools.newInstance(this).showText(getString(R.string.not_select_voice));
//                                        }
                                        return;
                                }
                                commitDataToPad();
                                break;
                        case R.id.tv_add_pic:
                                //选择图片
                                Intent intent2 = new Intent(EditMerchandiseActivity.this, MerchandiseChoosePicActivity.class);
                                if (isEdit) {
                                        intent2.putExtra("pic", merchandise.getPic());
                                        Logger.e(TAG, "编辑的图片地址==" + merchandise.getPic());
                                }
                                startActivityForResult(intent2, RESULT_CODE_PIC);
                                break;
                        case R.id.tv_add_voice:
                                //选择语音
                                if (isEdit){

                                        Intent intent3 = new Intent(EditMerchandiseActivity.this, SelectAudioTypeActivity.class);
                                        intent3.putExtra("isExit",true);
                                        intent3.putExtra("type",merchandise.getType());
                                        intent3.putExtra("path",merchandise.getVoice());

                                        startActivityForResult(intent3, RESULT_CODE_VOICE);

                                        return;
                                }
                                startActivityForResult(new Intent(EditMerchandiseActivity.this, SelectAudioTypeActivity.class), RESULT_CODE_VOICE);
                                break;
                }
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

                if (resultCode ==  RESULT_CANCELED){
                     return;
                }
                if (requestCode == RESULT_CODE_PIC) {

                                String path = data.getStringExtra("photos");
                                Logger.e(TAG, "返回的图片==" + path);
                                List<ChoosePicBean> list = JSON.parseArray(path, ChoosePicBean.class);
                                List<String> l = new ArrayList<>();
                                for (int i = 0; i < list.size(); i++) {
                                        l.add(list.get(i).getImagePath());
                                }
                                merchandise.setPic(l.toString());
                                Logger.e(TAG, "merchandise的图片==" + merchandise.getPic());
                }else if (requestCode == RESULT_CODE_VOICE) {

                        int type = data.getIntExtra("type", -1);
                        String path = data.getStringExtra("path");
                        Logger.e(TAG, "type = " + type + "path = " + path);
                        merchandise.setType(type);
                        merchandise.setVoice(path);
                }
        }



        /**
         * 提交数据到胸口
         */
        private void commitDataToPad() {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this,getString(R.string.data_upload));
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl("http://" + IpMsgConst.SOCKET_HOST2 + ":7755")
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(setTimeOut())
                        .build();
                SalesApi salesApi = retrofit.create(SalesApi.class);
                String values = JSON.toJSONString(merchandise);
                Logger.e(TAG, "上传数据" + values);
                Call<String> call = null;
                if (isEdit) {
                        call = salesApi.editMerchandise(values);
                        Logger.e(TAG, "编辑提交");
                }
                else {
                        call = salesApi.addMerchandise(values);
                        Logger.e(TAG, "新建提交");
                }
                call.enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                                if (response.body() != null) {
                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                        String body = response.body();

                                        Logger.e(TAG, "网络返回的数据" + body + "");
                                        Intent intent2 = new Intent(EditMerchandiseActivity.this, MerchandiseActivity.class);
                                        startActivity(intent2);
                                        finish();
                                        overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                                }
                                else {
                                        LoadingDialogUtils.closeDialog(dialogLoading);
                                }
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                t.fillInStackTrace();
                                Logger.e(TAG, "网络返回的数据错误信息 " + call.toString());
                                ToastTools.newInstance(EditMerchandiseActivity.this).showText(getString(R.string.submit_failure));

                        }
                });
        }
        private static final int TIMEOUT = 100;//超时时间100s

        /**
         * 设置超时
         * @return
         */
        private OkHttpClient setTimeOut(){
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .writeTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .readTimeout(TIMEOUT, TimeUnit.SECONDS)
                        .build();
                return client;

        }
}
